<?php
/**
 * Created by PhpStorm.
 * User: yf
 * Date: 2018/10/26
 * Time: 5:39 PM
 */

namespace App\HttpController\Api\VersionOne;

use App\HttpController\Api\ApiBase;
use App\Model\UserModel;
use EasySwoole\Http\Message\Status;
use EasySwoole\ORM\Exception\Exception;
use Throwable;


class VersionBase extends ApiBase
{
    // public才会根据协程清除
    public $who;
    // 不用验证header token白名单
    protected $whiteList = [];

    /**
     * onRequest
     * @param null|string $action
     * @return bool|null
     * @throws Throwable
     * @author yangzhenyu
     * Time: 13:49
     */
    function onRequest(?string $action): ?bool
    {
        if (parent::onRequest($action)) {
            // 白名单判断
            if (in_array($action, $this->whiteList)) {
                return true;
            }
            // 验证token
            $data = $this->getWho();
            if (is_numeric($data) && intval($data) <= 0) {
                $this->writeJson(Status::CODE_UNAUTHORIZED, '', '登入已过期');
                return false;
            }
            return true;
        }
        return false;
    }

    /**
     * getWho
     * @return UserModel|int|null
     * @throws \EasySwoole\Jwt\Exception
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws Exception
     * @throws Throwable
     * @author yangzhenyu
     * Time: 13:51
     */
    protected function getWho()
    {
        if ($this->who instanceof UserModel) {
            return $this->who;
        }

        $authorization = $this->request()->getHeader('authorization');

        if (empty($authorization)) {
            return null;
        }

        $authorizationArray = explode(" ", $authorization[0]);

        $userModel = new UserModel();
        $checkResult = $userModel->decryptToken($authorizationArray[1]);
        if (intval($checkResult) < 0) {
            return $checkResult;
        }

        $this->who = $userModel->get($checkResult);
        return $this->who;
    }
}
